package com.example.projectmanagement.controller.study;

import com.example.projectmanagement.dto.UserProfileDto;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.model.Role;
import com.example.projectmanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/study/profile")
@CrossOrigin
public class UserProfileController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前用户的学习档案
     */
    @GetMapping
    public ResponseEntity<User> getCurrentUserProfile() {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }

        // 获取用户信息
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (userOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        User user = userOpt.get();
        
        // 检查用户角色，管理员和讲师不需要学习档案
        if (shouldExcludeFromStudyProfile(user)) {
            return ResponseEntity.status(403).build(); // 管理员和讲师无权访问学习档案
        }

        return ResponseEntity.ok(user);
    }

    /**
     * 更新当前用户的学习档案
     */
    @PutMapping
    public ResponseEntity<User> updateCurrentUserProfile(@RequestBody UserProfileDto profileDto) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }

        // 获取用户信息
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (userOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        User user = userOpt.get();
        
        // 检查用户角色，管理员和讲师不需要学习档案
        if (shouldExcludeFromStudyProfile(user)) {
            return ResponseEntity.status(403).build(); // 管理员和讲师无权访问学习档案
        }

        try {
            User updatedUser = userService.updateUserProfile(currentUserId, profileDto);
            return ResponseEntity.ok(updatedUser);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 检查用户是否应该被排除在学习档案之外（管理员和讲师）
     */
    private boolean shouldExcludeFromStudyProfile(User user) {
        // 检查用户是否具有管理员或讲师角色
        List<Role> userRoles = userService.getUserRoles(user.getId());
        for (Role role : userRoles) {
            if ("ADMIN".equals(role.getRoleName()) || "LECTURER".equals(role.getRoleName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取当前认证用户的ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            // 根据用户名获取用户ID
            return userService.getUserByUsername(username).map(User::getId).orElse(null);
        }
        return null;
    }
}